<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { FormType } from './prizeDetail'
import { GetFukaOption, GetPrizeDataDetail, PostPrizeCreateData, PutPrizeModifyData } from '@/api/modules/fukaact'
import { GetOptionData } from '@/api/modules/voucher.ts'
import detailStore from '@/store/modules/NewCacheData'
import { GetAllData as GetProductOption } from '@/api/modules/merchandiseControl'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  fukaActId: '',
  prizeName: '',
  prizePic: '',
  prizeType: '',
  prizeKindid: '',
  usedUrl: '',
  prizeCoverpic: '',
  change: 0,
  stock: 0,
  used: 0,
  flag: 0,
  sort: 0,
  desp: '',
  prizeListBg: '',
})

const id = route.query.id as string

const rules = reactive({
  fukaActId: [
    { required: true, message: '请选择福卡活动', trigger: 'blur' },
  ],
  productId: [
    { required: true, message: '请选择要关联的商品', trigger: 'blur' },
  ],
})

// 图片上传赋值
function handleUploadSuccess(url: string, key: string) {
  // eslint-disable-next-line ts/ban-ts-comment
  // @ts-expect-error
  ruleForm.value[key] = url
}

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = { ...ruleForm.value }
      // console.log(params)
      if (params.prizeType === 2) {
        params.usedUrl = ''
      }

      if (id) {
        // 编辑
        params.fukaPrizeId = Number(id)
        PutPrizeModifyData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            router.push({
              name: 'fukaactPrizeList',
              query: {
                fukaActId: route.query.fukaActId,
              },
            })
          }
          else {
            ElMessage.error(`编辑失败。${res.errors}`)
          }
        })
      }
      else {
        // 添加
        // router.push({ name: 'fukaactPrizeList' })
        PostPrizeCreateData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.emptyFormData('fukaPrizeFrom')
            router.push({
              name: 'fukaactPrizeList',
              query: {
                fukaActId: route.query.fukaActId,
              },
            })
          }
          else {
            ElMessage.error(`添加失败。${res.errors}`)
          }
        })
      }
    }
    else {
      ElMessage.error('请检查表单')
    }
  })
}

const OptionList = reactive({
  fukaOption: [],
  productOption: [],
  CouponOption: [],
})

onMounted(async () => {
  if (id) {
    await GetPrizeDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
      }
    })
  }
  else {
    ruleForm.value = detailData.getFormData('fukaPrizeFrom')
  }

  watch(ruleForm, (newValue) => {
    if (!id) {
      detailData.rememberFormData('fukaPrizeFrom', newValue)
    }
  }, { deep: true })

  // 获取所有商品
  const ProductOption: any = await GetProductOption()
  if (ProductOption.succeeded) {
    OptionList.productOption = ProductOption.data
    nextTick(() => {
      OptionList.productOption = ProductOption.data
    })
  }

  // 获取所有商品
  const CouponOption: any = await GetOptionData()
  if (CouponOption.succeeded) {
    OptionList.CouponOption = CouponOption.data
    nextTick(() => {
      OptionList.CouponOption = CouponOption.data
    })
  }

  // 获取福卡活动
  const fukaData: any = await GetFukaOption()
  if (fukaData.succeeded) {
    OptionList.fukaOption = fukaData.data
    nextTick(() => {
      OptionList.fukaOption = fukaData.data
    })
  }
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="福卡活动" prop="fukaActId">
              <el-select v-model="ruleForm.fukaActId" filterable placeholder="请选择福卡活动">
                <el-option v-for="item in (OptionList.fukaOption as any[])" :key="item.fukaActId" :label="`${item.fukaActId}`" :value="item.fukaActId" />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="奖品名称" prop="prizeName">
              <el-input v-model="ruleForm.prizeName" placeholder="请输入奖品名称" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="状态">
              <el-switch
                v-model="ruleForm.flag"
                :active-value="1"
                :inactive-value="2"
                active-text="启用"
                inactive-text="停用"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="奖品类型" prop="prizeType">
              <!-- <el-select v-model="ruleForm.prizeType" placeholder="请选择状态">
                <el-option label="赠品券" :value="1" />
                <el-option label="实物" :value="2" />
                <el-option label="满减券" :value="3" />
              </el-select> -->
              <el-radio-group v-model="ruleForm.prizeType">
                <el-radio :value="1">
                  赠品券
                </el-radio>
                <el-radio :value="2">
                  实物
                </el-radio>
                <el-radio :value="3">
                  满减券
                </el-radio>
              </el-radio-group>
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.prizeType === 2" :md="8">
            <ElFormItem label="商品" prop="prizeKindid">
              <el-select v-model="ruleForm.prizeKindid" filterable placeholder="请选择商品">
                <el-option v-for="item in (OptionList.productOption as any[])" :key="item.productId" :label="`${item.productId}-${item.productName}`" :value="item.productId" />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.prizeType === 1" :md="8">
            <ElFormItem label="关联券" prop="prizeKindid">
              <el-select v-model="ruleForm.prizeKindid" filterable placeholder="请选择券">
                <el-option v-for="item in (OptionList.CouponOption as any[])" :key="item.id" :label="`${item.id}-${item.name}`" :value="item.id" />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.prizeType === 1" :md="8">
            <ElFormItem label="跳转地址" prop="usedUrl">
              <el-input v-model="ruleForm.usedUrl" placeholder="请输入跳转地址" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="自定义排序" prop="sort">
              <el-input v-model="ruleForm.sort" placeholder="请输入自定义排序" type="number" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="概率" prop="change">
              <el-input v-model="ruleForm.change" placeholder="请输入概率" type="number">
                <template #append>
                  ‱ ( 万分比 )
                </template>
              </el-input>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="库存" prop="stock">
              <el-input v-model="ruleForm.stock" placeholder="请输入库存" type="number" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="已消耗" prop="used">
              <el-input v-model="ruleForm.used" placeholder="请输入已消耗" type="number" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="16">
            <ElFormItem label="描述" prop="desp">
              <el-input v-model="ruleForm.desp" type="textarea" style="width: 500px;" placeholder="请输入描述" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="上传图片">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="奖品图" prop="prizePic">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.prizePic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'prizePic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="卡券背景图" prop="prizeListBg">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.prizeListBg" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'prizeListBg')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="奖品封面" prop="prizeCoverpic">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.prizeCoverpic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'prizeCoverpic')"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
